package com.ls.common.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author: xiaosu
 * @date: 2018-08-06  17:53
 */
@Configuration
@EnableCaching
public class CaffeineCacheConfig {


    public static final String CACHE_DEFAULT = "default";




    /**
     * 创建基于Caffeine的Cache Manager
     * @return
     */
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caches = new ArrayList<>();
        caches.add(new CaffeineCache(CACHE_DEFAULT, Caffeine.newBuilder().maximumSize(500)
                .expireAfterWrite(300, TimeUnit.SECONDS).build()));

        cacheManager.setCaches(caches);

        return cacheManager;
    }

}
